package com.ocom.human.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ocom.common.entity.human.EntityPersonnelFaceFeature;
import com.ocom.common.entity.human.EntityPersonnelInfo;
import com.ocom.common.enums.DataSourceEnum;
import com.ocom.common.enums.MasterSlaveEnum;
import com.ocom.common.request.human.FaceFeatureRequest;
import com.ocom.common.response.human.PerFaceFeatureResponse;
import com.ocom.common.utils.bdface.GsonUtils;
import com.ocom.common.utils.bdface.HttpUtil;
import com.ocom.common.vo.webapi.BDFaceFeature;
import com.ocom.human.dao.IDaoPersonnelFaceFeature;
import com.ocom.human.service.PersonnelFaceFeatureService;
import com.ocom.mysql.aspect.DataSourceAspect;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

@Slf4j
@Service
public class PersonnelFaceFeatureServiceImpl extends ServiceImpl<IDaoPersonnelFaceFeature, EntityPersonnelFaceFeature> implements PersonnelFaceFeatureService {


    private static final String CLIENT_ID = "ZfedCGbL7ZKR6ILKyOQGzOKF";
    private static final String CLIENT_SECRET = "LPj7mTe9vdEbqKdwagrI3EBVjGodFMw9";

    @Autowired
    IDaoPersonnelFaceFeature iDaoPersonnelFaceFeature;

    @Override
    @DataSourceAspect(type = DataSourceEnum.PART_DB, isMaster = MasterSlaveEnum.MASTER)
    public   boolean addEntityPersonnelFaceFeature(Long companyId, EntityPersonnelInfo entityPersonnelInfo, Logger logger){

        BDFaceFeature bdFaceFeature = faceFeature(entityPersonnelInfo.getPPhotoUrl2());

        logger.info("人脸特征值分数检测 LiM9sXTy 【{}】【{}】",entityPersonnelInfo,bdFaceFeature);

        EntityPersonnelFaceFeature entityPersonnelFaceFeature =new EntityPersonnelFaceFeature();
        entityPersonnelFaceFeature.setComId(entityPersonnelInfo.getComId());
        entityPersonnelFaceFeature.setPId(entityPersonnelInfo.getPId());
        entityPersonnelFaceFeature.setPhoto(entityPersonnelInfo.getPPhotoUrl2());
        entityPersonnelFaceFeature.setVersion("RV1109_3000");
        entityPersonnelFaceFeature.setErrCode(bdFaceFeature.getErrorCode());
        entityPersonnelFaceFeature.setErrMsg(bdFaceFeature.getErrorMsg());
        if(bdFaceFeature.getErrorCode() == 0l && bdFaceFeature.getResult().getFaceNum()>0l){
            entityPersonnelFaceFeature.setFaceNum(bdFaceFeature.getResult().getFaceNum());
            entityPersonnelFaceFeature.setFeature(bdFaceFeature.getResult().getFaceList().get(0).getFeature());
            entityPersonnelFaceFeature.setFaceProbability(bdFaceFeature.getResult().getFaceList().get(0).getFaceProbability());
            entityPersonnelFaceFeature.setLandmark72Probability(bdFaceFeature.getResult().getFaceList().get(0).getLandmark72_probability());
        }

        LambdaUpdateWrapper<EntityPersonnelFaceFeature> updateWrapper = new LambdaUpdateWrapper();
        updateWrapper.eq(EntityPersonnelFaceFeature::getComId,entityPersonnelInfo.getComId());
        updateWrapper.eq(EntityPersonnelFaceFeature::getPId,entityPersonnelInfo.getPId());
        updateWrapper.eq(EntityPersonnelFaceFeature::getPhoto,entityPersonnelInfo.getPPhotoUrl2());
        updateWrapper.set(EntityPersonnelFaceFeature::getErrCode,bdFaceFeature.getErrorCode());
        updateWrapper.set(EntityPersonnelFaceFeature::getErrMsg,bdFaceFeature.getErrorMsg());
        updateWrapper.set(EntityPersonnelFaceFeature::getVersion,"RV1109_3000");
        if(bdFaceFeature.getErrorCode() == 0l && bdFaceFeature.getResult().getFaceNum()>0l){
            updateWrapper.set(EntityPersonnelFaceFeature::getFaceNum,bdFaceFeature.getResult().getFaceNum());
            updateWrapper.set(EntityPersonnelFaceFeature::getFeature,bdFaceFeature.getResult().getFaceList().get(0).getFeature());
            updateWrapper.set(EntityPersonnelFaceFeature::getFaceProbability,bdFaceFeature.getResult().getFaceList().get(0).getFaceProbability());
            updateWrapper.set(EntityPersonnelFaceFeature::getLandmark72Probability,bdFaceFeature.getResult().getFaceList().get(0).getLandmark72_probability());
        }

        if(bdFaceFeature.getErrorCode() == 18l){
            Random random = new Random();
            // 生成100到500之间的随机数
            int sleepTime = random.nextInt(401) + 100; // 401 = (500 - 100 + 1)
            try {
                Thread.sleep(sleepTime);
          //      System.out.println("线程休眠了 " + sleepTime + " 毫秒");
            } catch (InterruptedException e) {
                e.printStackTrace(); // 处理中断异常
            }
        }

        return saveOrUpdate(entityPersonnelFaceFeature,updateWrapper);
    }

    @Override
    @DataSourceAspect(type = DataSourceEnum.PART_DB, isMaster = MasterSlaveEnum.SLAVE)
    public  Map<String, Object> featureList(Long companyId, FaceFeatureRequest request) {
        PageHelper.startPage(request.getPage(), request.getSize());
        Map<String, Object> map = new HashMap<>();
        List<PerFaceFeatureResponse> list = iDaoPersonnelFaceFeature.getPerFeature(request);
        PageInfo<PerFaceFeatureResponse> listPageInfo = new PageInfo<>(list);
        map.put("total", listPageInfo.getTotal());
        map.put("list", list);
        return map;
    }


    private BDFaceFeature faceFeature(String faceUrl ) {
        String version = "RV1109_3000" ;
        // 请求url
        //文档 https://cloud.baidu.com/doc/FACE/s/Okg7edktq
        String url = "https://aip.baidubce.com/rest/2.0/face/v1/feature";
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("image", faceUrl);
            map.put("image_type", "URL");
            map.put("version", version);

            String param = GsonUtils.toJson(map);

            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            String accessToken = getAuth(CLIENT_ID, CLIENT_SECRET);

            String result = HttpUtil.post(url, accessToken, "application/json", param);

            BDFaceFeature bdFaceFeature = JSON.parseObject(result, BDFaceFeature.class);

            log.info("faceDetect result:[{}]", bdFaceFeature.getErrorMsg());

            return bdFaceFeature;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getAuth(String ak, String sk) {
        // 获取token地址
        String authHost = "https://aip.baidubce.com/oauth/2.0/token?";
        String getAccessTokenUrl = authHost
                // 1. grant_type为固定参数
                + "grant_type=client_credentials"
                // 2. 官网获取的 API Key
                + "&client_id=" + ak
                // 3. 官网获取的 Secret Key
                + "&client_secret=" + sk;
        try {
            URL realUrl = new URL(getAccessTokenUrl);
            // 打开和URL之间的连接
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();

            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String result = "";
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }

            JSONObject jsonObject = JSON.parseObject(result);
            String access_token = jsonObject.getString("access_token");
            return access_token;
        } catch (Exception e) {
            log.error("获取token失败！");
            e.printStackTrace();
        }
        return null;
    }

}
